//
// This script is executed by Grails after plugin was installed to project.
// This script is a Gant script so you can use all special variables provided
// by Gant (such as 'baseDir' which points on project base dir). You can
// use 'ant' to access a global instance of AntBuilder
//
// For example you can create directory under project tree:
//
//    ant.mkdir(dir:"${basedir}/grails-app/jobs")
//

import groovy.xml.StreamingMarkupBuilder;

import java.io.FileInputStream;

if(!new File("${basedir}/flex-lib").exists())
	Ant.mkdir(dir:"${basedir}/flex-lib")

if(!new File("${basedir}/flex-src").exists())
	Ant.copy(todir: "${basedir}/flex-src", overwrite: false) {
		fileset(dir: "${pluginBasedir}/flex-src")
	}

if(!new File("${basedir}/html-template").exists())
	Ant.copy(todir: "${basedir}/html-template", overwrite: false) {
		fileset(dir: "${pluginBasedir}/html-template")
	}

if(!new File("${basedir}/web-app/WEB-INF/flex").exists())
	Ant.copy(todir: "${basedir}/web-app/WEB-INF/flex", overwrite: false) {
		fileset(dir: "${pluginBasedir}/web-app/WEB-INF/flex")
	}

if(!new File("${basedir}/.actionScriptProperties").exists())
	Ant.copy(todir: "${basedir}", overwrite: false) {
		fileset(dir:"${pluginBasedir}", includes:'.actionScriptProperties')
	}

if(!new File("${basedir}/.flexProperties").exists())
	Ant.copy(todir: "${basedir}", overwrite: false) {
		fileset(dir:"${pluginBasedir}", includes:'.flexProperties')
	}

def projectFile = new File("${basedir}/.project")
def xmlProject = new XmlSlurper().parse(projectFile)
ant.replace(file:"${basedir}/flex-src/conf/flex-config.xml", token:"ns-gflex",
		value:xmlProject.name)
ant.replace(file:"${basedir}/.actionScriptProperties", token:"ns-gflex",
		value:xmlProject.name)
def buildCommands = xmlProject.buildSpec.buildCommand
if(!buildCommands.find{it.name=='com.adobe.flexbuilder.project.flexbuilder'})
	buildCommands[buildCommands.size()-1] + {
		buildCommand{
			name('com.adobe.flexbuilder.project.flexbuilder')
			arguments{}
		}
	}

def natures=xmlProject.natures.nature
if(!natures.find{it=='com.adobe.flexbuilder.project.flexnature'})
	natures[natures.size()-1] + { nature('com.adobe.flexbuilder.project.flexnature') }
if(!natures.find{it=='com.adobe.flexbuilder.project.actionscriptnature'})
	natures[natures.size()-1] + { nature('com.adobe.flexbuilder.project.actionscriptnature') }

projectFile.withWriter {
	it<<'<?xml version="1.0" encoding="UTF-8"?>'
	it<< new StreamingMarkupBuilder().bindNode(xmlProject)
}
